//
//  ClubDynamicDetailCell.swift
//  77Club
//
//  Created by Apple on 2024/8/30.
//

import UIKit
import VersaPlayer
import MediaPlayer

//MARK: 动态详情内容cell
class ClubDynamicDetailCell: UITableViewCell {
    
    private let bannarCollectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    private let playerView = VersaPlayerView()
    private var controls = VersaPlayerControls()
    private let gameCollectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    private let contentLabel = c_make_ex(UITextView.self)
        .color("#2E3033").font(15.font_medium).end()
    private var imgs = [String]()
    private var imgTapValue = [String]()
    private var topicTapValue = [String]()
    private let pageView = c_make_ex(UIView.self)
        .bgColor("#F7F8FA".toColor.alpha(0.3)).corner(11).end()
    private let currenPage = c_make_ex(UILabel.self)
        .color(.white).font(12.font_semiBold).alignment(.right).end()
    private let totalPage = c_make_ex(UILabel.self)
        .color(.white.alpha(0.5)).font(9.font_semiBold).end()
    lazy var slider: VersaSeekbarSlider = {
       let makeView = VersaSeekbarSlider()
        //  最小值
        makeView.minimumValue = 0.0
        //  最大值
        makeView.maximumValue = 100.0
        //  设置默认值
//        makeView.setValue(sliderDefalutValue, animated: true)
        //  滑动条有值部分颜色
        makeView.minimumTrackTintColor = .white
        //  滑动条没有值部分颜色
        makeView.maximumTrackTintColor = .black.alpha(0.5)
        makeView.isUserInteractionEnabled = false
        makeView.setThumbImage(UIImage(), for: .normal)
        return makeView
    }()
    private let playButton = c_make_ex(UIButton.self)
        .image("Dynamic_detail_play",state: .selected).image("Dynamic_detail_pause").end()
    private let fullButton = c_make_ex(UIButton.self)
        .image("Dynamic_detail_full").end()
    private let voiceButton = c_make_ex(UIButton.self)
        .image("Dynamic_detail_aloud").image("Dynamic_detail_slience", state: .selected).end()
    private lazy var timeLabel = c_make_ex(UILabel.self)
        .color(.white).font(10.font_medium).alignment(.right).end()
    private var isFull = false
    private var games: [DynamicGamesModel]?
    
    /// 跳转游戏详情
    var toGameDetailVC: ((_ gameId: String) -> Void)?
    /// 话题主页
    var toTopicDetailVC: ((_ topicId: String) -> Void)?
    /// 点击视频
//    var didSelectVideo:((_:String)->())?
    /// 点击图片
    var didSelectImage:((_:Int,_:[String])->())?
    
    var model: ClubGameCircleModel?{
        didSet{
            guard let md = model else { return }
//            contentLabel.text = md.content
            if md.video.count > 0 {
                bannarCollectionView.isHidden = true
                playerView.isHidden = false
                if let url = URL.init(string: md.video) {
                    let item = VersaPlayerItem(url: url)
                    playerView.set(item: item)
                }
                contentLabel.topConstraint?.constant = 215
                pageView.isHidden = true
            }else if md.img.count > 0{
//                pageView.isHidden = false
                bannarCollectionView.isHidden = false
                playerView.isHidden = true
                if md.img.count > 1{
                    pageView.isHidden = false
                    totalPage.text = "/\(md.img.count)"
                    currenPage.text = "1"
                }else{
                    pageView.isHidden = true
                }                
                self.imgs = md.img
                bannarCollectionView.reloadData()
                contentLabel.topConstraint?.constant = 215
            }else{
                pageView.isHidden = true
                bannarCollectionView.isHidden = true
                playerView.isHidden = true
                contentLabel.topConstraint?.constant = 5
            }
//            likeButton.isSelected = md.is_zan
//            contentLabel.text = ""
            let attrString = self.createAttributedText(from: md.content)
            contentLabel.attributedText = attrString
            let size = CGSize(width: CGFloat.screenWidth - 104.0.Scale, height: .greatestFiniteMagnitude)
            let options: NSStringDrawingOptions = [.usesLineFragmentOrigin, .usesFontLeading]
                // 使用 boundingRect 方法计算高度
            let boundingRect = contentLabel.attributedText.boundingRect(with: size, options: options, context: nil)
            self.contentLabel.heightConstraint?.constant = ceil(boundingRect.height)
//            imgTapValue.reverse()
//            topicTapValue.reverse()
            self.games = md.games
            if let games = md.games, games.count > 0 {
                gameCollectionView.isHidden = false
                gameCollectionView.heightConstraint?.constant = 56.0.Scale
            }else{
                gameCollectionView.isHidden = true
                gameCollectionView.heightConstraint?.constant = 0
            }
            gameCollectionView.reloadData()
        }
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        backgroundColor = .clear
        contentView.backgroundColor = .clear
        
        contentView.subviews{
            bannarCollectionView
            playerView
            contentLabel
            pageView.subviews{
                currenPage
                totalPage
            }
            gameCollectionView
        }
        
        playerView.use(controls: controls)
        
        let bannarLayout = UICollectionViewFlowLayout()
        bannarLayout.minimumLineSpacing = 0
        bannarLayout.minimumInteritemSpacing = 0
        bannarLayout.scrollDirection = .horizontal
//        bannarLayout.itemSize = CGSize(width: .screenWidth, height: 210)
        
        bannarCollectionView.collectionViewLayout = bannarLayout
        bannarCollectionView.backgroundColor = .clear
        bannarCollectionView.register(ClubDynamicDetailBannarCell.self, forCellWithReuseIdentifier: ClubDynamicDetailBannarCell.description())
        bannarCollectionView.showsHorizontalScrollIndicator = false
        bannarCollectionView.delegate = self
        bannarCollectionView.dataSource = self
        bannarCollectionView.isPagingEnabled = true
        
        let gameLayout = UICollectionViewFlowLayout()
        gameLayout.minimumLineSpacing = 8.0.Scale
        gameLayout.minimumInteritemSpacing = 8.0.Scale
        gameLayout.scrollDirection = .horizontal
        gameLayout.sectionInset = UIEdgeInsets(top: 0, left: 16.0.Scale, bottom: 0, right: 0)
        
        gameCollectionView.collectionViewLayout = gameLayout
        gameCollectionView.backgroundColor = .clear
        gameCollectionView.register(ClubDynamicDetailGameCell.self, forCellWithReuseIdentifier: ClubDynamicDetailGameCell.description())
        gameCollectionView.showsHorizontalScrollIndicator = false
        gameCollectionView.delegate = self
        gameCollectionView.dataSource = self
        
        bannarCollectionView.leading(0).top(0).height(210).width(.screenWidth)
        playerView.leading(0).top(0).height(210).width(.screenWidth)
        contentLabel.leading(12).trailing(12).top(215)
        pageView.width(45).height(22).centerHorizontally()
        pageView.Bottom == bannarCollectionView.Bottom - 12
        totalPage.leading(22.5).centerVertically()
        currenPage.trailing(22.5).centerVertically()
        gameCollectionView.leading(0).height(56.0.Scale).width(.screenWidth).bottom(8.0.Scale)
        gameCollectionView.Top == contentLabel.Bottom + 16.0.Scale
        
        contentLabel.isUserInteractionEnabled = true
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
        contentLabel.addGestureRecognizer(tapGesture)
        
        contentLabel.isEditable = false
        contentLabel.isScrollEnabled = false
        contentLabel.isUserInteractionEnabled = true
        contentLabel.backgroundColor = .clear
        contentLabel.translatesAutoresizingMaskIntoConstraints = false
        contentLabel.textContainerInset = .zero
        contentLabel.textContainer.lineFragmentPadding = 0
        
        playerView.backgroundColor = .black
        playerView.playbackDelegate = self
        playerView.controls?.behaviour.showingControls = true
        playerView.isHidden = true
        
        controls.subviews{
            slider
            playButton
            fullButton
            voiceButton
            timeLabel
        }
        
        playButton.leading(0).bottom(0).size(44)
        slider.leading(48).height(1.5).width(205)
        slider.CenterY == playButton.CenterY
        fullButton.trailing(12).size(24)
        fullButton.CenterY == playButton.CenterY
        voiceButton.trailing(36).size(24)
        voiceButton.CenterY == playButton.CenterY
        timeLabel.trailing(60)
        timeLabel.CenterY == playButton.CenterY
        
        playButton.addTarget(self, action: #selector(clickPlayButton), for: .touchUpInside)
        voiceButton.addTarget(self, action: #selector(clickVoiceButton), for: .touchUpInside)
        fullButton.addTarget(self, action: #selector(clickFullButton), for: .touchUpInside)
        
        NotificationCenter.default.addObserver(self, selector: #selector(stopVideoPlay), name: .stopDetailAudioPlayer, object: nil)
    }
    
    @objc private func stopVideoPlay(){
        playerView.pause()
    }
    
    func createAttributedText(from text: String) -> NSMutableAttributedString {
        let attributedString = NSMutableAttributedString(string: text)
        
        // 默认字体和颜色
        attributedString.addAttribute(.foregroundColor, value: "#4B4C4D".toColor, range: NSRange(location: 0, length: attributedString.length))
        attributedString.addAttribute(.font, value: 15.font_regular!, range: NSRange(location: 0, length: attributedString.length))
        
        let nsText = text as NSString
        var count = 0
        var offset = 0 // 偏移量
        var index = 0  // 用于生成唯一的 actionType 标识
        
        // 正则匹配 # 和 [图片]
        let hashtagRegex = try! NSRegularExpression(pattern: "#[^\\s]+", options: [])
        let imageTextRegex = try! NSRegularExpression(pattern: "\\[图片\\](\\S+?) ", options: [])
        
        // **1. 优先处理 #标签**
        let hashtagMatches = hashtagRegex.matches(in: text, options: [], range: NSRange(location: 0, length: nsText.length))
        for match in hashtagMatches {
            let matchRange = match.range(at: 0)
            guard matchRange.location != NSNotFound else { continue }
            
            let hashtagRange = NSRange(location: matchRange.location + offset, length: matchRange.length)
            guard hashtagRange.location >= 0,
                  hashtagRange.location + hashtagRange.length <= attributedString.length else { continue }
            if var substring = attributedString.attributedSubstring(from: hashtagRange).string as String? {
                if let subjects = model?.subjects {
                    if substring.hasPrefix("#") {
                        substring.removeFirst()
                    }
                    if subjects.contains(where: { $0.name == substring }) {
                        index += 1
                        self.topicTapValue.append("hashtag_\(index)")
                        attributedString.addAttribute(.foregroundColor, value: "#E57617".toColor, range: hashtagRange) // 设置颜色
                        attributedString.addAttribute(NSAttributedString.Key("actionType"), value: "hashtag_\(index)", range: hashtagRange)
                    }
                }
            }
        }
        
        // **2. 处理 [图片]**
        let imageTextMatches = imageTextRegex.matches(in: text, options: [], range: NSRange(location: 0, length: nsText.length))
        for match in imageTextMatches {
            let fullMatchRange = NSRange(location: match.range(at: 0).location + offset, length: match.range(at: 0).length)
            let textRange = NSRange(location: match.range(at: 1).location + offset, length: match.range(at: 1).length)
            // 替换 [图片] 为图片
            let attachment = NSTextAttachment()
            attachment.image = UIImage(named: "Square_gameTag") // 替换为图片
            attachment.bounds = CGRect(x: 0, y: -7, width: 20, height: 20)
            let imageString = NSAttributedString(attachment: attachment)
            
            attributedString.replaceCharacters(in: NSRange(location: fullMatchRange.location, length: "[图片]".count), with: imageString)
            offset += imageString.length - "[图片]".count // 更新偏移量
            // 设置图片后面的文字颜色
            let updatedTextRange = NSRange(location: textRange.location + offset + (3 * count), length: textRange.length)
            if updatedTextRange.location + updatedTextRange.length <= attributedString.length {
                index += 1
                self.imgTapValue.append("imageText_\(index)")
                attributedString.addAttribute(.foregroundColor, value: "#3D9399".toColor, range: updatedTextRange)
                attributedString.addAttribute(NSAttributedString.Key("actionType"), value: "imageText_\(index)", range: updatedTextRange)
            }
            count += 1
        }
        
        return attributedString
    }
    
    @objc func handleTap(_ gesture: UITapGestureRecognizer) {
        let location = gesture.location(in: contentLabel)
        
        // 获取点击位置的字符索引
        if let position = contentLabel.closestPosition(to: location) {
            let characterIndex = contentLabel.offset(from: contentLabel.beginningOfDocument, to: position)
            
            // 确保 characterIndex 不超过富文本长度
            if characterIndex < contentLabel.attributedText.length {
                
                // 获取点击位置的属性
                let attributes = contentLabel.attributedText.attributes(at: characterIndex, effectiveRange: nil)
                
                // 检查是否存在 "actionType" 属性
                if let actionType = attributes[NSAttributedString.Key("actionType")] as? String {
                    
                    if actionType.hasPrefix("hashtag_") {
                        if let index = self.topicTapValue.firstIndex(of: actionType) {
                            let gamesId = model?.subjects?[index].subject_id ?? ""
                            self.toTopicDetailVC?(gamesId)
                        }
                    } else {
                        // 执行对应的操作
                        if let index = self.imgTapValue.firstIndex(of: actionType) {
                            let gamesId = model?.games?[index].gid ?? ""
                            self.toGameDetailVC?(gamesId)
                        }
                    }
                }
            }
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


//MARK: action
extension ClubDynamicDetailCell: VersaPlayerPlaybackDelegate {
    
    @objc private func clickPlayButton(){
        self.playButton.isSelected = !self.playButton.isSelected
        if self.playButton.isSelected {
            playerView.pause()
        }else{
            playerView.play()
        }
    }
    
    @objc private func clickFullButton(){
        
        self.isFull = !self.isFull
        self.playerView.setFullscreen(enabled: self.isFull)
    }
    
    @objc private func clickVoiceButton(){
        self.voiceButton.isSelected = !self.voiceButton.isSelected
        if self.voiceButton.isSelected {
            playerView.player.volume = 0
        }else{
            playerView.player.volume = 1
        }
    }
    
    func timeDidChange(player: VersaPlayer, to time: CMTime) {
        
        let seconds = CMTimeGetSeconds(time)
        let endTime = CMTimeGetSeconds(player.endTime())
        
        let currentT = CMTimeGetSeconds(time)
        let currentTStr = Int(currentT).toPlayTimeStr()
        let endTStr = Int(endTime).toPlayTimeStr()
        timeLabel.text = currentTStr + "/" + endTStr
        let totalT = self.playerView.player.endTime().seconds
        let progress = currentT / totalT * 100.0
        slider.value = Float(progress)
        
        if Int(seconds) == Int(endTime) {
            player.pause()
            let time:CMTime = CMTimeMakeWithSeconds(0.1, preferredTimescale: 1 * Int32(NSEC_PER_SEC))
            player.seek(to: time, toleranceBefore: CMTime.zero, toleranceAfter:CMTime.zero)
            player.play()
        }
        
    }
}

//MARK: action
extension ClubDynamicDetailCell: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if collectionView == bannarCollectionView {
            return imgs.count
        }
        return  games?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        if collectionView == bannarCollectionView {
            guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ClubDynamicDetailBannarCell.description(), for: indexPath) as? ClubDynamicDetailBannarCell else { return UICollectionViewCell() }
            cell.imgUrl = imgs[indexPath.row]
            return cell
        }
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ClubDynamicDetailGameCell.description(), for: indexPath) as? ClubDynamicDetailGameCell else { return UICollectionViewCell() }
        cell.model = games?[indexPath.row]
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        if collectionView == bannarCollectionView {
            if model?.img.count ?? 0 > 0 {
                didSelectImage?(indexPath.row,model?.img ?? [])
            }
        }else{
            
            let detailVC = ClubGameDetailViewController()
            detailVC.gameId = games?[indexPath.row].gid ?? ""
            UIApplication.topController()?.navigationController?.pushViewController(detailVC, animated: true)
        }
        
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        if collectionView == bannarCollectionView {
            return CGSize(width: .screenWidth, height: 210)
        }else{
            
            if games?.count ?? 0 > 1 {
                return CGSize(width: 250.0.Scale, height: 56.0.Scale)
            }else{
                return CGSize(width: CGFloat.screenWidth - 32.0.Scale, height: 56.0.Scale)
            }
        }
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {

        guard let collectionView = scrollView as? UICollectionView else { return }
            
            let visibleCells = collectionView.visibleCells
            for cell in visibleCells {
                // 获取 cell 在 CollectionView 中的位置
                if let indexPath = collectionView.indexPath(for: cell) {
                    // 判断该 cell 是否完全可见
                    let cellFrame = collectionView.layoutAttributesForItem(at: indexPath)?.frame ?? .zero
                    let cellVisibleRect = collectionView.bounds.intersection(cellFrame)

                    if cellVisibleRect == cellFrame {
                        self.currenPage.text = "\(indexPath.row + 1)"
                    }
                }
            }
    }
}


class ClubDynamicDetailommitCell: UITableViewCell, UITableViewDelegate, UITableViewDataSource, RaeNetworkProtocol {
    
    private let bgView = c_make_ex(UIView.self)
        .bgColor(.white).corner(12.0.Scale).end()
    private let iconImageView = c_make_ex(UIImageView.self)
        .corner(20.0.Scale).mode(.scaleAspectFill).end()
    private let moreButton = c_make_ex(UIButton.self)
        .image("Mine_Commit_more").end()
    private let nameLabel = ActiveLabel()
    private let timeLabel = c_make_ex(UILabel.self)
        .color("#AEB0B3").font(11.font_medium).end()
    private let contentLabel = ActiveLabel()
    private let subLabel = c_make_ex(UILabel.self)
        .color("#7B7D80").font(10.font_medium).alignment(.right).end()
    private let likeButton = c_make_ex(UIButton.self)
        .image("Square_like").image("Square_liked", state: .selected).end()
    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        tableView.register(ClubCommitSonCell.self)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.separatorStyle = .none
//        tableView.estimatedRowHeight = 136.0.Scale
        tableView.isScrollEnabled = false
        return tableView
    }()
    
    var likeCommitBlock: ((_ commitID: String) -> Void)?
    var showMoreView: ((_ commitID: String, _ uid: String) -> Void)?
    
    private var sonData: [ClubDynamicDetailCommentModel]?
    private var forumSonData: [ClubGameCommunityDetailCommentModel]?

    var model: ClubGameDetailCommentListModel? {
        didSet{
            guard let md = model else { return }
            
            iconImageView.loadImage(url: md.touxiang)
            configActiveStyle(name: "", content: md.content)
//            nameLabel.text = md.user_name
            timeLabel.text = md.time
//            var commentCount = ""
//            if  md.num != "0" {
//                commentCount = md.num
//            }
            var zanCount = ""
            if md.zan != "0" {
                zanCount = md.zan
            }
//            subLabel.text = commentCount + "评论 · " + zanCount + "点赞"
            subLabel.text = zanCount + "点赞"
            likeButton.isSelected = md.is_zan
            var author = ""
            if  md.is_author {
                author = "作者 "
            }
            let user_Name = author + md.user_name
            configNameActiveStyle(name: author, content: user_Name)
        }
        
    }
    
    var detailCommit: ClubDynamicDetailCommentModel? {
        didSet{
            guard let md = detailCommit else { return }
            iconImageView.loadImage(url: md.face)
            configActiveStyle(name: "", content: md.content)
            nameLabel.text = md.pet_name
            timeLabel.text = md.time
//            let num = md.data_num ?? 0
//            var numString = ""
//            if num > 0 {
//                numString = "\(num)"
//            }
            var zanCount = ""
            if md.zan != "0" {
                zanCount = md.zan
            }
//            subLabel.text = numString + "评论 · " + zanCount + "点赞"
            subLabel.text = zanCount + "点赞"
            likeButton.isSelected = md.is_zan
            var tableViewH = 0.0
            if let arr = md.data, arr.count > 0 {
                self.sonData = arr
                tableViewH = self.calculateHeight(dataArray: arr)
                self.tableView.isHidden = false
                self.tableView.reloadData()
            }else{
                self.tableView.isHidden = true
                self.tableView.heightConstraint?.constant = 0
            }
            
            let height = md.content.calculateTextHeight(font: 15.font_medium!, width: CGFloat.screenWidth - 104.0.Scale) + 99.0.Scale + tableViewH
            self.bgView.heightConstraint?.constant = height
            var author = ""
            if  md.is_author {
                author = "作者 "
            }
            let user_Name = author + md.pet_name
            configNameActiveStyle(name: author, content: user_Name)
            moreButton.isHidden = false
        }
    }
    
    var forumModel: ClubGameCommunityDetailCommentModel? {
        didSet{
            guard let md = forumModel else { return }
            iconImageView.loadImage(url: md.face)
//            contentLabel.text = md.content
//            nameLabel.text = md.pet_name
            if md.p_pet_name.count > 0 {
                let name = "@" + md.p_pet_name + ":"
                let content = "回复给@" + md.p_pet_name + ":" + md.content
                configActiveStyle(name: name, content: content)
            }else{
                configActiveStyle(name: "", content: md.content)
            }
            var author = ""
            if  md.is_author {
                author = "作者 "
            }
            let user_Name = author + md.pet_name
            configNameActiveStyle(name: author, content: user_Name)
            timeLabel.text = md.time
//            let num = md.list.count
//            var numString = ""
//            if num > 0 {
//                numString = "\(num)"
//            }
            var zanCount = ""
            if md.good != "0" {
                zanCount = md.good
            }
//            subLabel.text = numString + "评论 · " + zanCount + "点赞"
            subLabel.text = zanCount + "点赞"
            likeButton.isSelected = md.is_good
            var tableViewH = 0.0
            if md.list.count > 0 {
                self.forumSonData = md.list
                tableViewH = self.calculateForumDetailHeight(dataArray: md.list)
                self.tableView.isHidden = false
                self.tableView.reloadData()
            }else{
                self.tableView.isHidden = true
                self.tableView.heightConstraint?.constant = 0
            }
            
            let height = md.content.calculateTextHeight(font: 15.font_medium!, width: CGFloat.screenWidth - 104.0.Scale) + 99.0.Scale + tableViewH
            self.bgView.heightConstraint?.constant = height
            moreButton.isHidden = false
        }
    }
    
    private func configNameActiveStyle(name: String, content: String) {
        let customType = ActiveType.custom(pattern: name)
        nameLabel.isShowUnderLine = false
        nameLabel.font = 12.font_semiBold
        nameLabel.numberOfLines = 0
        nameLabel.textAlignment = .left
        nameLabel.enabledTypes = [customType]
        nameLabel.text = content
        nameLabel.textColor = "#4B4C4D".toColor
        nameLabel.customColor[customType] = "#FF7500".toColor
    }
    
    private func configActiveStyle(name: String, content: String) {
        var huifu = ""
        if name.count > 0 {
            huifu = "回复给"
        }
        let customType = ActiveType.custom(pattern: huifu)
        let customType1 = ActiveType.custom(pattern: name)
        contentLabel.isShowUnderLine = false
        contentLabel.font = 15.font_medium
        contentLabel.numberOfLines = 0
        contentLabel.textAlignment = .left
        contentLabel.enabledTypes = [customType, customType1]
        contentLabel.text = content
        contentLabel.textColor = "#4B4C4D".toColor
        contentLabel.customColor[customType] = "#7D7E80".toColor
        contentLabel.customColor[customType1] = "#3D9399".toColor
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        initUI()
    }
    
    func initUI() -> Void {
        selectionStyle = UITableViewCell.SelectionStyle.none
        backgroundColor = UIColor.clear
        
        contentView.subviews{
            bgView.subviews{
                moreButton
                iconImageView
                nameLabel
                timeLabel
                contentLabel
                subLabel
                likeButton
                tableView
            }
        }
        
        bgView.leading(12.0.Scale).trailing(12.0.Scale).top(0).bottom(12.0.Scale).height(300)
        moreButton.trailing(5.0.Scale).top(12.0.Scale).size(44.0.Scale)
        iconImageView.leading(12.0.Scale).top(16.0.Scale).size(40.0.Scale)
        nameLabel.leading(64.0.Scale).top(20.0.Scale).trailing(55.0.Scale)
        timeLabel.leading(64.0.Scale).top(38.0.Scale).trailing(15.0.Scale)
        contentLabel.leading(64.0.Scale).top(55.0.Scale).trailing(16.0.Scale)
        likeButton.trailing(8.0.Scale).size(44.0.Scale)
        likeButton.Top == contentLabel.Bottom
        subLabel.trailing(56.0.Scale)
        subLabel.CenterY == likeButton.CenterY
        tableView.leading(64.0.Scale).trailing(0).height(0).bottom(0)
        tableView.Top == likeButton.Bottom
        
        moreButton.isHidden = true
        likeButton.addTarget(self, action: #selector(clickLikeButton), for: .touchUpInside)
        moreButton.addTarget(self, action: #selector(clickMoreButton), for: .touchUpInside)
    }
    
    @objc private func clickMoreButton(){

        if let md = detailCommit {
            showMoreView?(md.id,md.uid_des)
        }
        if let md = forumModel {
            showMoreView?(md.id,md.uid_des)
        }
        
    }
    
    @objc private func clickLikeButton(){
        
        if let ID = model?.id {
            likeCommitBlock?(ID)
        }
        if let ID = detailCommit?.id {
//            likeCommitBlock?(ID)
            guard let md = detailCommit else { return }
            if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
                Task{
                    ToastUtil.show()
                    let models = await network.request(.dynamicLike(type: "1", dynamicID: ID),isShowError: false)
                    ToastUtil.dismiss()
                    likeButton.isSelected = !likeButton.isSelected
                    if likeButton.isSelected {
                        "点赞成功".toast_success
                    }else{
                        "已取消点赞".toast_success
                    }
                    let strArray = subLabel.text!.components(separatedBy: " · ")
                    var zanString = strArray.last ?? ""
                    if zanString == "点赞" {
                        zanString = "1点赞"
                    }else{
                        if likeButton.isSelected {
                            zanString = ClubGlobalTool.shared.calculateNumberInString(text: zanString)
                        }else{
                            zanString = ClubGlobalTool.shared.subtractionNumberInString(text: zanString)
                            if zanString == "0点赞"{
                                zanString = "点赞"
                            }
                        }
                    }
//                    let num = md.data_num ?? 0
//                    var numString = ""
//                    if num > 0 {
//                        numString = "\(num)"
//                    }
//                    subLabel.text = numString + "评论 · " + zanString
                    subLabel.text = zanString
                }
            }else{
                UIApplication.topController()?.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
            }
        }
        if let ID = forumModel?.id {
//            likeCommitBlock?(ID)
            guard let md = forumModel else { return }
            if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
                Task{
                    ToastUtil.show()
                    let _ = await self.network.request(.likeStrategyPost(pid: ID, puid: "", type: "1"))
                    ToastUtil.dismiss()
                    likeButton.isSelected = !likeButton.isSelected
                    if likeButton.isSelected {
                        "点赞成功".toast_success
                    }else{
                        "已取消点赞".toast_success
                    }
                    let strArray = subLabel.text!.components(separatedBy: " · ")
                    var zanString = strArray.last ?? ""
                    if zanString == "点赞" {
                        zanString = "1点赞"
                    }else{
                        if likeButton.isSelected {
                            zanString = ClubGlobalTool.shared.calculateNumberInString(text: zanString)
                        }else{
                            zanString = ClubGlobalTool.shared.subtractionNumberInString(text: zanString)
                            if zanString == "0点赞"{
                                zanString = "点赞"
                            }
                        }
                    }
//                    let num = md.list.count
//                    var numString = ""
//                    if num > 0 {
//                        numString = "\(num)"
//                    }
//                    subLabel.text = numString + "评论 · " + zanString
                    subLabel.text = zanString
                }
            }else{
                UIApplication.topController()?.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
            }
        }
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        if let sonArray = sonData {
            return sonArray.count
        }
        if let sonArray = forumSonData {
            return sonArray.count
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "ClubCommitSonCell", for: indexPath) as! ClubCommitSonCell
        if let sonModel = sonData?[indexPath.row] {
            cell.model = sonModel
        }
        if let forumModel = forumSonData?[indexPath.row] {
            cell.forumModel = forumModel
        }
        
//        cell.likeBlock = {forumModel
//            self.likeAction(type: "0", id: self.dynamicID)
//        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
//        let detailVC = HWGameDetailController()
//        detailVC.gameId = dataModel?[indexPath.row].id ?? ""
//        self.navigationController?.pushViewController(detailVC, animated: true)
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

        var height = 0.0
        
        var content = ""
        if let sonModel = sonData?[indexPath.row].content {
            content = sonModel
        }
        if let forumModel = forumSonData?[indexPath.row].content {
            content = forumModel
        }
        height += 32.0.Scale
        let contentH = content.calculateTextHeight(font: 15.font_medium!, width: CGFloat.screenWidth - 138.0.Scale) + 34.0
        height += contentH
        
        return height
    }
    
    private func calculateHeight(dataArray: [ClubDynamicDetailCommentModel]) -> CGFloat{
        
        var height = 0.0
        for md in dataArray {
            height += 32.0.Scale
            let contentH = md.content.calculateTextHeight(font: 15.font_medium!, width: CGFloat.screenWidth - 138.0.Scale) + 34.0
            height += contentH
        }
        
        DispatchQueue.main.asyncAfter(deadline: .now()) {
            
            self.tableView.heightConstraint?.constant = height
        }
        return height
    }
    
    private func calculateForumDetailHeight(dataArray: [ClubGameCommunityDetailCommentModel]) -> CGFloat{
        
        var height = 0.0
        for md in dataArray {
            height += 32.0.Scale
            let contentH = md.content.calculateTextHeight(font: 15.font_medium!, width: CGFloat.screenWidth - 138.0.Scale) + 34.0
            height += contentH
        }
        
        DispatchQueue.main.asyncAfter(deadline: .now()) {
            
            self.tableView.heightConstraint?.constant = height
        }
        return height
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
}


class ClubCommitSonCell: UITableViewCell, RaeNetworkProtocol {
    
    private let iconImageView = c_make_ex(UIImageView.self)
        .corner(12.0.Scale).mode(.scaleAspectFill).end()
    private let nameLabel = ActiveLabel()
    private let timeLabel = c_make_ex(UILabel.self)
        .color("#AEB0B3").font(11.font_medium).end()
    private let contentLabel = c_make_ex(UILabel.self)
        .color("#47494D").font(15.font_medium)
        .line(0).end()
    private let subLabel = c_make_ex(UILabel.self)
        .color("#7B7D80").font(10.font_medium).alignment(.right).end()
    private let likeButton = c_make_ex(UIButton.self)
        .image("Square_detail_like").image("Square_detail_liked", state: .selected).end()

    var model: ClubDynamicDetailCommentModel? {
        didSet{
            guard let md = model else { return }
            iconImageView.loadImage(url: md.face)
            if md.huifu.count > 0 {
                contentLabel.text = md.huifu + md.content
            }else{
                contentLabel.text = md.content
            }
            timeLabel.text = " · " + md.time
            var zan = ""
            if md.zan != "0" {
                zan = md.zan
            }
            subLabel.text = zan + "点赞"
            likeButton.isSelected = md.is_zan
            var author = ""
            if  md.is_author {
                author = "作者 "
            }
            let user_Name = author + md.pet_name
            configNameActiveStyle(name: author, content: user_Name)
        }
    }
    
    var forumModel: ClubGameCommunityDetailCommentModel? {
        didSet{
            guard let md = forumModel else { return }
            iconImageView.loadImage(url: md.face)
            contentLabel.text = md.content
            timeLabel.text = " · " + md.time
            var zan = ""
            if md.good != "0" {
                zan = md.good
            }
            subLabel.text = zan + "点赞"
            likeButton.isSelected = md.is_good
            var author = ""
            if  md.is_author {
                author = "作者 "
            }
            let user_Name = author + md.pet_name
            configNameActiveStyle(name: author, content: user_Name)
        }
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        initUI()
    }
    
    func initUI() -> Void {
        
        selectionStyle = UITableViewCell.SelectionStyle.none
        backgroundColor = UIColor.clear
        
        contentView.subviews{
            iconImageView
            nameLabel
            timeLabel
            contentLabel
            subLabel
            likeButton
        }
        
        iconImageView.leading(0).top(8.0.Scale).size(24.0.Scale)
        nameLabel.leading(32.0.Scale).trailing(>=75.0.Scale)
        nameLabel.CenterY == iconImageView.CenterY
        timeLabel.trailing(16.0.Scale)
        timeLabel.Leading == nameLabel.Trailing
        timeLabel.CenterY == nameLabel.CenterY
        contentLabel.leading(32.0.Scale).top(32.0.Scale).trailing(18.0.Scale)
        likeButton.trailing(18.0.Scale).size(24.0.Scale).bottom(10.0.Scale)
        likeButton.Top == contentLabel.Bottom
        subLabel.trailing(46.0.Scale)
        subLabel.CenterY == likeButton.CenterY
        
        likeButton.addTarget(self, action: #selector(clickLikeButton), for: .touchUpInside)
    }
 
    private func configNameActiveStyle(name: String, content: String) {
        let customType = ActiveType.custom(pattern: name)
        nameLabel.isShowUnderLine = false
        nameLabel.font = 11.font_semiBold
        nameLabel.numberOfLines = 0
        nameLabel.textAlignment = .left
        nameLabel.enabledTypes = [customType]
        nameLabel.text = content
        nameLabel.textColor = "#2E3033".toColor
        nameLabel.customColor[customType] = "#FF7500".toColor
    }
    
    @objc private func clickLikeButton(){
        
        if let ID = model?.id {
            guard let md = model else { return }
            if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
                //点赞
                Task {
                    ToastUtil.show()
                    let models = await network.request(.dynamicLike(type: "1", dynamicID: ID),isShowError: false)
                    if models.isSuccess {
                        ToastUtil.dismiss()
                        "点赞成功".toast_success
                        likeButton.isSelected = !likeButton.isSelected
                        if subLabel.text == "点赞" {
                            subLabel.text = "1点赞"
                        }else{
                            if likeButton.isSelected {
                                subLabel.text = ClubGlobalTool.shared.calculateNumberInString(text: subLabel.text ?? "")
                            }else{
                                subLabel.text = ClubGlobalTool.shared.subtractionNumberInString(text: subLabel.text ?? "")
                            }
                        }
                    }
                }
            }else{
                //登录
                UIApplication.topController()?.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
            }
        }
        if let ID = forumModel?.id {
            
            guard let md = forumModel else { return }
            if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
                Task{
                    ToastUtil.show()
                    let _ = await self.network.request(.likeStrategyPost(pid: ID, puid: "", type: "1"))
                    ToastUtil.dismiss()
                    "点赞成功".toast_success
                    likeButton.isSelected = !likeButton.isSelected
                    if subLabel.text == "点赞" {
                        subLabel.text = "1点赞"
                    }else{
                        if likeButton.isSelected {
                            subLabel.text = ClubGlobalTool.shared.calculateNumberInString(text: subLabel.text ?? "")
                        }else{
                            subLabel.text = ClubGlobalTool.shared.subtractionNumberInString(text: subLabel.text ?? "")
                        }
                    }
                }
            }else{
                UIApplication.topController()?.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
            }
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
}

//MARK: 动态详情Bannar cell
class ClubDynamicDetailBannarCell: UICollectionViewCell {
    
    private let iconImageView = c_make_ex(UIImageView.self)
        .mode(.scaleAspectFit).bgColor(.black).end()
    private let shadowView = c_make_ex(UIView.self)
        .bgColor(.black.alpha(0.1)).end()
    var imgUrl: String = "" {
        didSet{
            iconImageView.loadImage(url: imgUrl)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.backgroundColor = .clear
        backgroundColor = .clear
        
        contentView.subviews{
            iconImageView
            shadowView
        }
        
        iconImageView.fillContainer()
        shadowView.fillContainer()
    }
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

//MARK: 动态详情game cell
class ClubDynamicDetailGameCell: UICollectionViewCell {
    
    private let bgView = c_make_ex(UIView.self)
        .corner(8).bgColor("#47494D").end()
    private let iconImageView = c_make_ex(UIImageView.self)
        .corner(8).mode(.scaleAspectFill).end()
    private let nameLabel = c_make_ex(UILabel.self)
        .color(.white).font(12.font_semiBold).end()
    private var gameSubLabel = c_make_ex(UILabel.self)
        .color(.white.alpha(0.85)).font(10.font_medium).end()
    
    var model: DynamicGamesModel?{
        didSet{
            guard let md = model else { return }
            
            iconImageView.loadImage(url: md.icon)
            nameLabel.text = md.name
            let tagStr = md.biaoqian.replacingOccurrences(of: ",", with: "·")
            let subStr = md.point + " · " + tagStr
            gameSubLabel.text = subStr
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.backgroundColor = .clear
        backgroundColor = .clear
        
        contentView.subviews{
            bgView.subviews{
                iconImageView
                nameLabel
                gameSubLabel
            }
        }
        
        bgView.fillContainer()
        iconImageView.leading(12).size(32).centerVertically()
        nameLabel.leading(56).top(12).trailing(16)
        gameSubLabel.leading(56).top(32).trailing(16).height(16)
    }
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}


class ClubCommitEmptyCell: UITableViewCell {
    
    private let emptyView = ClubEmptyCommitView()
    
    var firstCommitBlock: (() -> Void)?
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        initUI()
    }
    
    func initUI() -> Void {
        
        selectionStyle = UITableViewCell.SelectionStyle.none
        backgroundColor = UIColor.clear
        
        contentView.subviews{
            emptyView
        }
        
        emptyView.leading(0).trailing(0).top(35.0.Scale).height(300.0.Scale).bottom(0)
        
        emptyView.commitBlock = {
            self.firstCommitBlock?()
        }
    }
 
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
}
